package com.ruoyi.common.utils.wx;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.WxV3PayConfig;
import com.wechat.pay.contrib.apache.httpclient.auth.*;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
import com.wechat.pay.java.core.http.*;
import com.wechat.pay.java.service.partnerpayments.nativepay.model.PrepayResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.springframework.stereotype.Component;

import java.io.IOException;

import com.wechat.pay.java.core.Config;

@Slf4j
@Component
public class WxMiniPayUtils {

    public static HttpClient httpClient;

    public static Verifier verifier;


    /**
     * 初始化 HttpClient
     * @throws IOException
     */
    public static void initWXPayClient() throws IOException {
        try {
            // 加载商户私钥（privateKey：私钥字符串）
//            PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(WxV3PayConfig.privateKey);
//
//            // 也可使用证书 查询商户证书序列号
////            X509Certificate wechatPayCert = PemUtil.loadCertificate(new ByteArrayInputStream(StaticVariable.WX_PAY_CERT.getBytes(StandardCharsets.UTF_8)));
////            String serialNo = wechatPayCert.getSerialNumber().toString(16).toUpperCase();
//
//            String serialNo = WxV3PayConfig.mchSerialNo;
//            //merchantId:商户号,serialNo:商户证书序列号
//            // 获取证书管理器实例
//            CertificatesManager certificatesManager = CertificatesManager.getInstance();
//            // 向证书管理器增加需要自动更新平台证书的商户信息
//            certificatesManager.putMerchant(WxV3PayConfig.Mch_ID, new WechatPay2Credentials(WxV3PayConfig.Mch_ID,
//                    new PrivateKeySigner(serialNo, merchantPrivateKey)), WxV3PayConfig.apiV2Key.getBytes(StandardCharsets.UTF_8));
//            // 从证书管理器中获取verifier
//            //版本>=0.4.0可使用 CertificatesManager.getVerifier(mchId) 得到的验签器替代默认的验签器。
//            // 它会定时下载和更新商户对应的微信支付平台证书 （默认下载间隔为UPDATE_INTERVAL_MINUTE）。
//            verifier = certificatesManager.getVerifier(WxV3PayConfig.Mch_ID);
//
//            //创建一个httpClient
//            httpClient = WechatPayHttpClientBuilder.create()
//                    .withMerchant(WxV3PayConfig.Mch_ID, serialNo, merchantPrivateKey)
//                    .withValidator(new WechatPay2Validator(verifier)).build();


            Config config =
                    new RSAPublicKeyConfig.Builder()
                            .merchantId(WxV3PayConfig.Mch_ID)
                            .privateKeyFromPath(WxV3PayConfig.privateKey_Path)
                            .publicKeyFromPath(WxV3PayConfig.publicKey_Path)
                            .publicKeyId(WxV3PayConfig.PUB_KEY_ID)
                            .merchantSerialNumber(WxV3PayConfig.mchSerialNo)
                            .apiV3Key(WxV3PayConfig.apiV3Key)
                            .build();

               httpClient =
                    new DefaultHttpClientBuilder()
                            .config(config)
                            .connectTimeoutMs(500)
                            .build();



        }
//        catch (IOException e) {
//            e.printStackTrace();
//            log.error("加载秘钥文件失败");
//        } catch (GeneralSecurityException e) {
//            e.printStackTrace();
//            log.error("获取平台证书失败");
//        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭 HttpClient
     * @throws IOException
     */
    public static void closeWXClient() throws IOException {
        if (httpClient != null) {
            try {
               // httpClient.
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建微信支付订单
     * @param openId 用户唯一标识
     * @param orderId 订单id
     * @param amount 支付价格(单位分)
     * @param description 订单说明
     * @return
     * @throws Exception
     */
    public static JSONObject creatOrderJSAPI(String openId, String orderNumber, Integer amount, String description) throws Exception {
        try {
            initWXPayClient();
            HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi");
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");

            String reqdata = "{"
                    + "\"amount\": {"
                    + "\"total\": "+amount+","
                    + "\"currency\": \"CNY\""
                    + "},"
                    + "\"mchid\": \""+ WxV3PayConfig.Mch_ID +"\","
                    + "\"description\": \""+description+"\","
                    + "\"notify_url\": \""+WXPayConstants.WECHAT_PAY_NOTIFY_URL+"\","
                    + "\"payer\": {"
                    + "\"openid\": \""+openId+"\"" + "},"
                    + "\"out_trade_no\": \""+orderNumber+"\","
                    + "\"goods_tag\": \"WXG\","
                    + "\"appid\": \""+ WxV3PayConfig.APP_ID+"\"" + "}";

            httpPost.setEntity(new StringEntity(reqdata, "utf-8"));


            HttpHeaders headers = new HttpHeaders();
            headers.addHeader(Constant.ACCEPT, MediaType.APPLICATION_JSON.getValue());
            headers.addHeader(Constant.CONTENT_TYPE, MediaType.APPLICATION_JSON.getValue());
            HttpRequest httpRequest =
                    new HttpRequest.Builder()
                            .httpMethod(HttpMethod.POST)
                            .url("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi")
                            .headers(headers)
                            .body(createRequestBody(reqdata))
                            .build();
            HttpResponse<PrepayResponse> httpResponse = httpClient.execute(httpRequest,  PrepayResponse.class);

           // System.out.println(httpResponse);
            ResponseBody responseBody=httpResponse.getBody();
            responseBody.toString();
           // CloseableHttpResponse response = httpClient.execute(httpPost, PrepayResponse.class);
           ;
            return  JSONObject.parseObject(responseBody.toString());
        }catch (Exception e){
            e.printStackTrace();
            log.error("创建微信支付订单失败");
        }finally {
            closeWXClient();
        }
        return null;
    }




   private static RequestBody createRequestBody(Object request) {
//       Gson gson = new Gson();
//       JsonElement element = gson.fromJson(jsonString, JsonElement.class);
       // return new JsonRequestBody.Builder().body(toJson(request)).build();
       return new JsonRequestBody.Builder().body(JSONUtil.toJsonStr(request)).build();
      // return  null;
    }

    //////////////////////
    public void  testPay(){

    }


}
